﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace PayloadTracker.VOR
{
    [Serializable]
    public class VOR
    {
        private Coordinate m_Position;
        public PayloadTracker.Coordinate Position
        {
            get { return m_Position; }
            set { m_Position = value; }
        }
        
        private float m_MagneticDeclinationOffset;
        [XmlAttribute]
        public float MagneticDeclinationOffset
        {
            get { return m_MagneticDeclinationOffset; }
            set { m_MagneticDeclinationOffset = value; }
        }

        private string m_Name;
        [XmlAttribute]
        public string Name
        {
            get { return m_Name; }
            set { m_Name = value; }
        }

        public VOR(string name,Coordinate position, float magneticDeclinationOffset)
        {
            Name = name;
            Position = position;
            MagneticDeclinationOffset = magneticDeclinationOffset;
        }
        private VOR()
        {

        }

        
        /// <summary>
        /// returns nautical mile distance to coordinate c
        /// </summary>
        /// <param name="c">coordinate to calculate distance</param>
        /// <returns>distance in nautical miles.</returns>
        public double DistanceTo(Coordinate c)
        {
            return Position.DistanceTo(c, Coordinate.DistanceType.NauticalMiles);
        }
        /// <summary>
        /// Gets corrected beating between a Coordinate and a VOR
        /// </summary>
        /// <returns>returns bearing in degrees</returns>
        public double GetCorrectedBearingTo(Coordinate c)
        {

            var rdist = Position.DistanceTo(c, Coordinate.DistanceType.Radian);

            var t1 = Math.Sin(c.LatRadians()) - Math.Sin(Position.LatRadians()) * Math.Cos(rdist);
            var t2 = Math.Cos(Position.LatRadians()) * Math.Sin(rdist);
            var t3 = t1 / t2;

            double radbearing = 0;

            if (Math.Sin(c.LongRadians() - Position.LongRadians()) < 0)
                radbearing = Math.Atan(-t3 / Math.Sqrt(-t3 * t3 + 1)) + 2 * Math.Atan(1);
            else
                radbearing = 2 * Math.PI - (Math.Atan(-t3 / Math.Sqrt(-t3 * t3 + 1)) + 2 * Math.Atan(1));


            double degbaering = radbearing * 180 / Math.PI;

            double offset = degbaering - MagneticDeclinationOffset;

            return offset >= 0 ? offset : 360 + offset;
        }
    }
}
